package com.turnengine.client.local.faction;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import com.javabi.common.lang.ThreadSafe;
import com.turnengine.client.local.faction.bean.IFaction;
import com.turnengine.client.local.faction.enums.FactionUnited;

@ThreadSafe
public class FactionCache implements IFactionCache {

	private Set<IFaction> factionSet = new ConcurrentSkipListSet<IFaction>();

	public FactionCache() {
	}

	public FactionCache(Collection<IFaction> factions) {
		addFactions(factions);
	}

	@Override
	public void clear() {
		factionSet.clear();
	}

	@Override
	public int size() {
		return factionSet.size();
	}

	@Override
	public boolean addFaction(IFaction faction) {
		return factionSet.add(faction);
	}

	@Override
	public int addFactions(Collection<IFaction> factions) {
		int added = 0;
		for (IFaction faction : factions) {
			if (addFaction(faction)) {
				added++;
			}
		}
		return added;
	}

	@Override
	public boolean containsById(int id) {
		for (IFaction faction : factionSet) {
			if (faction.getId() == id) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean containsByName(String name) {
		for (IFaction faction : factionSet) {
			if (faction.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public IFaction getById(int id) {
		for (IFaction faction : factionSet) {
			if (faction.getId() == id) {
				return faction;
			}
		}
		throw new IllegalArgumentException("id=" + id + " in " + factionSet);
	}

	@Override
	public IFaction getByName(String name) {
		for (IFaction faction : factionSet) {
			if (faction.getName().equals(name)) {
				return faction;
			}
		}
		throw new IllegalArgumentException("name: " + name + " in " + factionSet);
	}

	@Override
	public List<IFaction> getByUnited(FactionUnited factioned) {
		List<IFaction> set = new ArrayList<IFaction>();
		for (IFaction faction : factionSet) {
			if (faction.getUnited().equals(factioned)) {
				set.add(faction);
			}
		}
		return set;
	}

	@Override
	public Iterator<IFaction> iterator() {
		return getAll().iterator();
	}

	@Override
	public List<IFaction> getAll() {
		return new ArrayList<IFaction>(factionSet);
	}

	@Override
	public String toString() {
		return getAll().toString();
	}

}
